<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>微软账号登录</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px;
    }
    
    .login-container {
      background: white;
      border-radius: 12px;
      box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
      padding: 40px;
      width: 100%;
      max-width: 450px;
      text-align: center;
      transition: transform 0.3s ease;
    }
    
    .login-container:hover {
      transform: translateY(-5px);
    }
    
    h2 {
      color: #333;
      margin-bottom: 30px;
      font-size: 28px;
      font-weight: 600;
    }
    
    .logo {
      width: 80px;
      height: 80px;
      margin: 0 auto 20px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 36px;
      font-weight: bold;
    }
    
    .login-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      border: none;
      padding: 15px 30px;
      font-size: 18px;
      border-radius: 50px;
      cursor: pointer;
      transition: all 0.3s ease;
      width: 100%;
      font-weight: 600;
      letter-spacing: 0.5px;
      box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }
    
    .login-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }
    
    .login-btn:active {
      transform: translateY(0);
    }
    
    .divider {
      margin: 30px 0;
      position: relative;
      height: 1px;
      background-color: #eee;
    }
    
    .divider::after {
      content: '或';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background: white;
      padding: 0 15px;
      color: #999;
      font-size: 14px;
    }
    
    h3 {
      color: #333;
      margin-bottom: 20px;
      font-size: 20px;
      font-weight: 500;
    }
    
    .input-group {
      margin-bottom: 20px;
    }
    
    #manualUrl {
      width: 100%;
      padding: 15px;
      border: 2px solid #eee;
      border-radius: 8px;
      font-size: 16px;
      transition: border-color 0.3s ease;
      outline: none;
    }
    
    #manualUrl:focus {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }
    
    .confirm-btn {
      background: #4CAF50;
      color: white;
      border: none;
      padding: 15px 30px;
      font-size: 16px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      width: 100%;
      font-weight: 600;
    }
    
    .confirm-btn:hover {
      background: #45a049;
      transform: translateY(-2px);
      box-shadow: 0 4px 15px rgba(76, 175, 80, 0.3);
    }
    
    .instructions {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 20px;
      margin-top: 30px;
      text-align: left;
    }
    
    .instructions h4 {
      color: #333;
      margin-bottom: 10px;
      font-size: 16px;
    }
    
    .instructions ol {
      padding-left: 20px;
    }
    
    .instructions li {
      margin-bottom: 8px;
      color: #666;
      font-size: 14px;
      line-height: 1.5;
    }
    
    .footer {
      margin-top: 30px;
      color: #999;
      font-size: 12px;
    }
  </style>
</head>
<body>
  <div class="login-container">
    <div class="logo">MS</div>
    <h2>微软账号登录</h2>
    
    <button id="loginBtn" class="login-btn">点击登录微软账号</button>
    
    <div class="divider"></div>
    
    <h3>手动输入跳转地址</h3>
    <div class="input-group">
      <input type="text" id="manualUrl" placeholder="请输入跳转地址">
    </div>
    <button id="confirmBtn" class="confirm-btn">确定</button>
    
    <div class="instructions">
      <h4>手动输入说明：</h4>
      <ol>
        <li>登陆网页的时候，可能需要在电脑端浏览器进行登陆，因为手机浏览器可能无法打开浏览器控制台</li>
        <li>在新打开的网页进行登陆，登陆之前要在网页中按F12打开浏览器控制台，选择网络(Network)选项卡进行监听</li>
        <li>在登陆完成后，会有一条网络请求状态标红表示无法跳转网页</li>
        <li>右键点击这条标红的网络请求，选择"检查"或"查看详细信息"</li>
        <li>在请求详情中找到响应头(Response Headers)，找到Location字段的值</li>
        <li>将Location字段的值复制到上方输入框中，格式为ms-xal-xxxxxxxx</li>
        <li>点击确定按钮完成登录</li>
      </ol>
    </div>
    
    <div class="footer">
      Microsoft Account Login Service
    </div>
  </div>

  <script>
    // 先进入等待页面，等待后端返回登录地址
    document.getElementById("loginBtn").onclick = async () => {
      // 弹出提示框提醒用户打开浏览器的控制台网络检测
      alert("请在新打开的标签页中登录，并确保浏览器的控制台网络检测已开启，以便捕获登录后的跳转地址。");
      
      try {
        const response = await fetch('/api/get_sisu_login_url');
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        
        // 直接在新标签页中打开获取到的登录链接
        window.open(data.url, "_blank");
      } catch (error) {
        console.error('获取登录链接失败:', error);
      }
    };

    window.addEventListener("message", async (event) => {
      if (typeof event.data === "object" && event.data.code && event.data.state) {
        try {
          const response = await fetch('/api/set_sisu_code_and_state', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              code: event.data.code,
              state: event.data.state
            })
          });
          
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          
          console.log("已发送 code 和 state 到后端:", event.data.code, event.data.state);
        } catch (error) {
          console.error('提交code和state失败:', error);
        }
      }
    });

    // ✅ 手动解析跳转地址
    document.getElementById("confirmBtn").onclick = async () => {
      const input = document.getElementById("manualUrl").value.trim();
      try {
        const url = new URL(input.replace(/^ms-xal-[^:]+/, 'https')); // 替换协议以便解析
        let code = url.searchParams.get("code");
        let state = url.searchParams.get("state");
    
        if (!code || !state) throw new Error("缺少参数");
    
        // 处理转义字符
        code = decodeURIComponent(code);
        state = decodeURIComponent(state);
    
        const response = await fetch('/api/set_sisu_code_and_state', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            code: code,
            state: state
          })
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        console.log("手动解析成功，已发送 code 和 state");
    
        // ✅ 跳转到根目录
        window.location.href = "/";
      } catch (err) {
        alert("解析失败，请检查输入格式是否正确！");
        console.error("解析失败:", err);
      }
    };
  </script>
</body>
</html>